package com.vegetable.modules.service.inbound.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.inbound.PurchaseDeliveryReturn;
import com.vegetable.modules.entity.inbound.PurchaseDeliveryReturnDetail;
import com.vegetable.modules.entity.inbound.po.PurchaseDeliveryReturnPO;
import com.vegetable.modules.mapper.inbound.PurchaseDeliveryReturnDetailMapper;
import com.vegetable.modules.mapper.inbound.PurchaseDeliveryReturnMapper;
import com.vegetable.modules.service.inbound.IPurchaseDeliveryReturnService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 入库-采购收货退货 服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-09
 */
@Slf4j
@Service
public class PurchaseDeliveryReturnServiceImpl extends ServiceImpl<PurchaseDeliveryReturnMapper, PurchaseDeliveryReturn> implements IPurchaseDeliveryReturnService {

    @Resource
    private PurchaseDeliveryReturnDetailMapper purchaseDeliveryReturnDetailMapper;
    
    @Override
    public List<PurchaseDeliveryReturn> getReturnsByDeliveryId(Long deliveryId) {
        return baseMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PurchaseDeliveryReturn>()
                .eq("delivery_id", deliveryId)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveReturn(PurchaseDeliveryReturn purchaseDeliveryReturn) throws Exception {
        try {
            // 设置创建时间
            if (purchaseDeliveryReturn.getCreateTime() == null) {
                purchaseDeliveryReturn.setCreateTime(new Date());
            }
            
            // 保存退货主表信息
            if (purchaseDeliveryReturn.getId() == null) {
                // 新增
                baseMapper.insert(purchaseDeliveryReturn);
            } else {
                // 更新
                baseMapper.updateById(purchaseDeliveryReturn);
                
                // 删除原有的明细记录
                purchaseDeliveryReturnDetailMapper.delete(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PurchaseDeliveryReturnDetail>()
                        .eq("return_id", purchaseDeliveryReturn.getId())
                );
            }
            
            // 保存退货明细
            if (purchaseDeliveryReturn.getReturnDetails() != null && !purchaseDeliveryReturn.getReturnDetails().isEmpty()) {
                for (PurchaseDeliveryReturnDetail detail : purchaseDeliveryReturn.getReturnDetails()) {
                    detail.setId(null); // 确保是新增
                    detail.setReturnId(purchaseDeliveryReturn.getId());
                    purchaseDeliveryReturnDetailMapper.insert(detail);
                }
            }
            
            return R.data(purchaseDeliveryReturn);
        } catch (Exception e) {
            log.error("保存退货信息失败", e);
            throw new Exception("保存退货信息失败: " + e.getMessage());
        }
    }

    @Override
    public R getReturnDetail(Long id) {
        PurchaseDeliveryReturn returnInfo = baseMapper.selectById(id);
        if (returnInfo != null) {
            // 查询退货明细
            List<PurchaseDeliveryReturnDetail> details = purchaseDeliveryReturnDetailMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PurchaseDeliveryReturnDetail>()
                    .eq("return_id", id));
            returnInfo.setReturnDetails(details);
        }
        return R.data(returnInfo);
    }

    @Override
    public R queryPage(PurchaseDeliveryReturnPO po) {
        try {
            IPage<PurchaseDeliveryReturn> page = new Page<>(po.getPage(), po.getLimit());
            IPage<PurchaseDeliveryReturn> result = baseMapper.queryPage(page, po);
            return R.data(result);
        } catch (Exception e) {
            log.error("分页查询退货记录失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }
}